<template>
  <div class="follow-up-communication">
    <el-row :gutter="10" class="mb8">
      <el-col :span="2">
        <el-button type="primary" icon="Plus" @click="openTaskDialog('create')">新建任务</el-button>
      </el-col>
      <el-col :span="2">
        <el-button type="primary" plain icon="Phone" @click="openCallLogDialog">通话记录</el-button>
      </el-col>
      <el-col :span="2">
        <el-button type="primary" plain icon="Message" @click="openSmsLogDialog">短信记录</el-button>
      </el-col>
      <el-col :span="2">
        <el-button type="primary" plain icon="Email" @click="openEmailDialog">邮件管理</el-button>
      </el-col>
      <el-col :span="2">
        <el-button type="primary" plain icon="FileText" @click="openTemplateDialog">模板库</el-button>
      </el-col>
      <el-col :span="2" :offset="10">
        <el-input v-model="searchQuery" placeholder="搜索任务..." prefix-icon="Search" @keyup.enter="handleSearch" />
      </el-col>
    </el-row>

    <el-card class="filter-card" v-if="filterVisible">
      <el-form :model="filterForm" inline label-width="80px">
        <el-form-item label="任务类型">
          <el-select v-model="filterForm.taskType" placeholder="全部">
            <el-option label="全部" value="" />
            <el-option label="电话" value="phone" />
            <el-option label="上门" value="visit" />
            <el-option label="发资料" value="sendMaterial" />
            <el-option label="面试安排" value="interview" />
          </el-select>
        </el-form-item>
        <el-form-item label="优先级">
          <el-select v-model="filterForm.priority" placeholder="全部">
            <el-option label="全部" value="" />
            <el-option label="高" value="high" />
            <el-option label="中" value="medium" />
            <el-option label="低" value="low" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filterForm.status" placeholder="全部">
            <el-option label="全部" value="" />
            <el-option label="未开始" value="pending" />
            <el-option label="进行中" value="inProgress" />
            <el-option label="已完成" value="completed" />
            <el-option label="已逾期" value="overdue" />
          </el-select>
        </el-form-item>
        <el-form-item label="到期日">
          <el-date-picker v-model="filterForm.dueDate" type="date" placeholder="选择日期" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilter">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-table :data="taskList" style="width: 100%" border v-loading="loading">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column prop="id" label="任务ID" width="80" />
      <el-table-column prop="title" label="任务标题" width="200" />
      <el-table-column prop="taskType" label="任务类型" width="100">
        <template #default="{ row }">
          <el-tag :type="getTaskTypeColor(row.taskType)">{{ getTaskTypeName(row.taskType) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="priority" label="优先级" width="80">
        <template #default="{ row }">
          <el-tag :type="getPriorityColor(row.priority)">{{ getPriorityName(row.priority) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="studentName" label="学员姓名" width="100" />
      <el-table-column prop="dueDate" label="到期日" width="180" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusColor(row.status)">{{ getStatusName(row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createBy" label="创建人" width="100" />
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" align="center" width="200" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="Eye" @click="viewTaskDetails(scope.row)">查看</el-button>
          <el-button link type="success" icon="Edit" @click="openTaskDialog('edit', scope.row)">编辑</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDeleteTask(scope.row.id)">删除</el-button>
          <el-button link type="warning" v-if="scope.row.status !== 'completed'" icon="Check" @click="handleCompleteTask(scope.row.id)">完成</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 任务详情对话框 -->
    <el-dialog :title="taskDialog.title" v-model="taskDialog.open" width="600px" append-to-body>
      <el-form :model="taskForm" ref="taskFormRef" label-width="100px">
        <el-form-item label="任务标题" prop="title">
          <el-input v-model="taskForm.title" placeholder="请输入任务标题" />
        </el-form-item>
        <el-form-item label="任务类型" prop="taskType">
          <el-select v-model="taskForm.taskType" placeholder="请选择任务类型">
            <el-option label="电话" value="phone" />
            <el-option label="上门" value="visit" />
            <el-option label="发资料" value="sendMaterial" />
            <el-option label="面试安排" value="interview" />
          </el-select>
        </el-form-item>
        <el-form-item label="学员" prop="studentId">
          <el-select v-model="taskForm.studentId" placeholder="请选择学员">
            <el-option v-for="student in studentList" :key="student.id" :label="student.name" :value="student.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-select v-model="taskForm.priority" placeholder="请选择优先级">
            <el-option label="高" value="high" />
            <el-option label="中" value="medium" />
            <el-option label="低" value="low" />
          </el-select>
        </el-form-item>
        <el-form-item label="到期日" prop="dueDate">
          <el-date-picker v-model="taskForm.dueDate" type="date" placeholder="选择日期" />
        </el-form-item>
        <el-form-item label="重复规则" prop="repeatRule">
          <el-select v-model="taskForm.repeatRule" placeholder="请选择重复规则">
            <el-option label="不重复" value="none" />
            <el-option label="每天" value="daily" />
            <el-option label="每周" value="weekly" />
            <el-option label="每月" value="monthly" />
          </el-select>
        </el-form-item>
        <el-form-item label="提醒时间" prop="reminderTime">
          <el-time-picker v-model="taskForm.reminderTime" placeholder="选择时间" />
        </el-form-item>
        <el-form-item label="任务描述" prop="description">
          <el-input v-model="taskForm.description" type="textarea" placeholder="请输入任务描述" :rows="4" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="taskDialog.open = false">取 消</el-button>
          <el-button type="primary" @click="saveTask">保 存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 跟进历史时间轴 -->
    <el-dialog title="跟进历史" v-model="historyDialog.open" width="800px" append-to-body>
      <el-timeline>
        <el-timeline-item v-for="item in followUpHistory" :key="item.id" :timestamp="item.time" placement="top">
          <el-card>
            <el-card-header bordered="false">
              <div class="card-header">
                <span>{{ item.title }}</span>
                <span class="card-header-extra" :class="getHistoryTypeClass(item.type)">{{ getHistoryTypeName(item.type) }}</span>
              </div>
            </el-card-header>
            <el-card-body>
              <p>{{ item.content }}</p>
              <div v-if="item.attachments && item.attachments.length > 0" class="attachments">
                <p class="attachment-title">附件：</p>
                <el-link v-for="attachment in item.attachments" :key="attachment.id" :href="attachment.url" target="_blank" type="primary" :underline="false" class="attachment-link">{{ attachment.name }}</el-link>
              </div>
            </el-card-body>
          </el-card>
        </el-timeline-item>
      </el-timeline>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="historyDialog.open = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { listTask, getTask, addTask, updateTask, deleteTask, completeTask, listFollowUpHistory, listStudent } from '@/api/followUpCommunication';

// 组件实例
const { proxy } = getCurrentInstance();

// 状态管理
const loading = ref(false);
const searchQuery = ref('');
const filterVisible = ref(false);
const currentView = ref('all');

// 数据管理
const taskList = ref([]);
const studentList = ref([]);
const followUpHistory = ref([]);

// 表单数据
const filterForm = reactive({
  taskType: '',
  priority: '',
  status: '',
  dueDate: ''
});

const taskForm = reactive({
  id: '',
  title: '',
  taskType: '',
  studentId: '',
  priority: 'medium',
  dueDate: '',
  repeatRule: 'none',
  reminderTime: '',
  description: ''
});

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 对话框状态
const taskDialog = reactive({
  open: false,
  title: '新建任务'
});

const historyDialog = reactive({
  open: false,
  studentId: ''
});

// 生命周期
onMounted(() => {
  loadTaskList();
  loadStudentList();
});

// 加载任务列表
function loadTaskList() {
  loading.value = true;
  const params = {
    pageNum: pagination.currentPage,
    pageSize: pagination.pageSize,
    keyword: searchQuery.value,
    ...filterForm
  };
  listTask(params).then(response => {
    taskList.value = response.rows;
    pagination.total = response.total;
    loading.value = false;
  }).catch(error => {
    console.error('加载任务列表失败:', error);
    loading.value = false;
  });
}

// 加载学员列表
function loadStudentList() {
  listStudent({ pageNum: 1, pageSize: 1000 }).then(response => {
    studentList.value = response.rows;
  }).catch(error => {
    console.error('加载学员列表失败:', error);
  });
}

// 打开任务对话框
function openTaskDialog(type, task = {}) {
  if (type === 'create') {
    taskDialog.title = '新建任务';
    Object.keys(taskForm).forEach(key => {
      taskForm[key] = '';
    });
    taskForm.priority = 'medium';
    taskForm.repeatRule = 'none';
  } else {
    taskDialog.title = '编辑任务';
    Object.assign(taskForm, { ...task });
  }
  taskDialog.open = true;
}

// 保存任务
function saveTask() {
  proxy.$refs.taskFormRef.validate((valid) => {
    if (valid) {
      const request = taskForm.id ? updateTask : addTask;
      request(taskForm).then(response => {
        ElMessage.success('操作成功');
        taskDialog.open = false;
        loadTaskList();
      }).catch(error => {
        ElMessage.error('操作失败: ' + error.message);
      });
    }
  });
}

// 查看任务详情
function viewTaskDetails(task) {
  getTask(task.id).then(response => {
    Object.assign(taskForm, response);
    taskDialog.title = '任务详情';
    taskDialog.open = true;
  }).catch(error => {
    ElMessage.error('获取任务详情失败: ' + error.message);
  });
}

// 删除任务
function handleDeleteTask(id) {
  ElMessageBox.confirm('确定要删除该任务吗？', '确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteTask(id).then(response => {
      ElMessage.success('删除成功');
      loadTaskList();
    }).catch(error => {
      ElMessage.error('删除失败: ' + error.message);
    });
  });
}

// 完成任务
function handleCompleteTask(id) {
  ElMessageBox.confirm('确定要标记该任务为已完成吗？', '确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info'
  }).then(() => {
    completeTask(id).then(response => {
      ElMessage.success('操作成功');
      loadTaskList();
    }).catch(error => {
      ElMessage.error('操作失败: ' + error.message);
    });
  });
}

// 查看跟进历史
function viewFollowUpHistory(studentId) {
  historyDialog.studentId = studentId;
  listFollowUpHistory({ studentId }).then(response => {
    followUpHistory.value = response;
    historyDialog.open = true;
  }).catch(error => {
    ElMessage.error('获取跟进历史失败: ' + error.message);
  });
}

// 搜索任务
function handleSearch() {
  pagination.currentPage = 1;
  loadTaskList();
}

// 打开筛选
function openFilter() {
  filterVisible.value = !filterVisible.value;
}

// 处理筛选
function handleFilter() {
  pagination.currentPage = 1;
  loadTaskList();
}

// 重置筛选
function resetFilter() {
  Object.keys(filterForm).forEach(key => {
    filterForm[key] = '';
  });
  loadTaskList();
}

// 分页处理
function handleSizeChange(size) {
  pagination.pageSize = size;
  loadTaskList();
}

function handleCurrentChange(current) {
  pagination.currentPage = current;
  loadTaskList();
}

// 格式化任务类型
function getTaskTypeName(type) {
  const map = {
    'phone': '电话',
    'visit': '上门',
    'sendMaterial': '发资料',
    'interview': '面试安排'
  };
  return map[type] || type;
}

// 任务类型颜色
function getTaskTypeColor(type) {
  const map = {
    'phone': 'primary',
    'visit': 'success',
    'sendMaterial': 'info',
    'interview': 'warning'
  };
  return map[type] || 'default';
}

// 格式化优先级
function getPriorityName(priority) {
  const map = {
    'high': '高',
    'medium': '中',
    'low': '低'
  };
  return map[priority] || priority;
}

// 优先级颜色
function getPriorityColor(priority) {
  const map = {
    'high': 'danger',
    'medium': 'warning',
    'low': 'success'
  };
  return map[priority] || 'default';
}

// 格式化状态
function getStatusName(status) {
  const map = {
    'pending': '未开始',
    'inProgress': '进行中',
    'completed': '已完成',
    'overdue': '已逾期'
  };
  return map[status] || status;
}

// 状态颜色
function getStatusColor(status) {
  const map = {
    'pending': 'default',
    'inProgress': 'primary',
    'completed': 'success',
    'overdue': 'danger'
  };
  return map[status] || 'default';
}

// 跟进历史类型名称
function getHistoryTypeName(type) {
  const map = {
    'call': '通话记录',
    'sms': '短信记录',
    'email': '邮件记录',
    'visit': '上门拜访',
    'task': '任务完成'
  };
  return map[type] || type;
}

// 跟进历史类型样式
function getHistoryTypeClass(type) {
  const map = {
    'call': 'type-call',
    'sms': 'type-sms',
    'email': 'type-email',
    'visit': 'type-visit',
    'task': 'type-task'
  };
  return map[type] || '';
}

// 打开通话记录对话框
function openCallLogDialog() {
  // 通话记录对话框逻辑，这里仅作占位
  ElMessage.info('通话记录功能开发中');
}

// 打开短信记录对话框
function openSmsLogDialog() {
  // 短信记录对话框逻辑，这里仅作占位
  ElMessage.info('短信记录功能开发中');
}

// 打开邮件管理对话框
function openEmailDialog() {
  // 邮件管理对话框逻辑，这里仅作占位
  ElMessage.info('邮件管理功能开发中');
}

// 打开模板库对话框
function openTemplateDialog() {
  // 模板库对话框逻辑，这里仅作占位
  ElMessage.info('模板库功能开发中');
}
</script>

<style scoped>
.follow-up-communication {
  padding: 20px;
}

.mb8 {
  margin-bottom: 8px;
}

.filter-card {
  margin-bottom: 16px;
}

.pagination-container {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

.attachments {
  margin-top: 10px;
}

.attachment-title {
  font-weight: bold;
  margin-bottom: 5px;
}

.attachment-link {
  margin-right: 10px;
  display: inline-block;
  margin-bottom: 5px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header-extra {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.type-call {
  background-color: #e6f7ff;
  color: #1890ff;
}

.type-sms {
  background-color: #fff1f0;
  color: #f5222d;
}

.type-email {
  background-color: #f0f9eb;
  color: #52c41a;
}

.type-visit {
  background-color: #fff7e6;
  color: #faad14;
}

.type-task {
  background-color: #ebf4ff;
  color: #40a9ff;
}
</style>